package com.yzt.message.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.yzt.zhuju.event.RxBus;

import com.yzt.zhuju.event.main.ShowSoftKeyboardEvent;
import com.yzt.zhuju.widget.emticonnskeyboard.EmoticonsEditText;
import com.yzt.p_base.utils.KeyboardUtils;
import com.yzt.p_base.utils.LogDataUtils;
import com.yzt.message.R;
import com.yzt.message.R.id;
import com.yzt.message.custom.RXDiceMessageContent;
import com.yzt.message.observer.ChatInputLoadManager;
import com.yzt.message.widget.chatinput.widget.ChatInputView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

import io.rong.common.RLog;
import io.rong.imkit.IMCenter;
import io.rong.imkit.MessageItemLongClickAction;
import io.rong.imkit.MessageItemLongClickActionManager;
import io.rong.imkit.RongIM;
import io.rong.imkit.config.RongConfigCenter;
import io.rong.imkit.conversation.MessageListAdapter;
import io.rong.imkit.conversation.messgelist.processor.IConversationUIRenderer;
import io.rong.imkit.conversation.messgelist.viewmodel.MessageItemLongClickBean;
import io.rong.imkit.conversation.messgelist.viewmodel.MessageViewModel;
import io.rong.imkit.event.Event;
import io.rong.imkit.event.uievent.InputBarEvent;
import io.rong.imkit.event.uievent.PageDestroyEvent;
import io.rong.imkit.event.uievent.PageEvent;
import io.rong.imkit.event.uievent.ScrollEvent;
import io.rong.imkit.event.uievent.ScrollMentionEvent;
import io.rong.imkit.event.uievent.ScrollToEndEvent;
import io.rong.imkit.event.uievent.ShowLongClickDialogEvent;
import io.rong.imkit.event.uievent.ShowWarningDialogEvent;
import io.rong.imkit.event.uievent.SmoothScrollEvent;
import io.rong.imkit.event.uievent.ToastEvent;
import io.rong.imkit.feature.mention.DraftHelper;
import io.rong.imkit.feature.mention.RongMentionManager;
import io.rong.imkit.manager.SendImageManager;
import io.rong.imkit.manager.SendMediaManager;
import io.rong.imkit.manager.hqvoicemessage.HQVoiceMsgDownloadManager;
import io.rong.imkit.model.UiMessage;
import io.rong.imkit.widget.refresh.api.RefreshLayout;
import io.rong.imkit.widget.refresh.listener.OnLoadMoreListener;
import io.rong.imkit.widget.refresh.listener.OnRefreshListener;
import io.rong.imkit.picture.PictureSelector;
import io.rong.imkit.picture.config.PictureMimeType;
import io.rong.imkit.picture.entity.LocalMedia;
import io.rong.imkit.utils.PermissionCheckUtil;
import io.rong.imkit.widget.adapter.BaseAdapter;
import io.rong.imkit.widget.adapter.IViewProviderListener;
import io.rong.imkit.widget.adapter.ViewHolder;
import io.rong.imkit.widget.dialog.OptionsPopupDialog;
import io.rong.imkit.widget.refresh.SmartRefreshLayout;
import io.rong.imkit.widget.refresh.constant.RefreshState;
import io.rong.imkit.widget.refresh.wrapper.RongRefreshHeader;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.message.TextMessage;
import rx.Subscription;

/**
 * 复制融云5.x版本 代码 ConversationFragment
 * 并加入本地需求代码
 */
public class MessageFragment extends Fragment implements View.OnTouchListener,
        OnRefreshListener, OnLoadMoreListener, View.OnClickListener, IViewProviderListener<UiMessage> {

    private final String TAG = MessageFragment.class.getSimpleName();

    protected SmartRefreshLayout mRefreshLayout;
    protected RecyclerView mList;
    protected LinearLayoutManager mLinearLayoutManager;
    protected MessageListAdapter mAdapter = this.onResolveAdapter();
    protected MessageViewModel mMessageViewModel;
    protected TextView mNewMessageNum;
    protected TextView mUnreadHistoryMessageNum;
    protected TextView mUnreadMentionMessageNum;
    public static final int REQUEST_CODE_FORWARD = 104;
    private boolean onViewCreated = false;
    private String mTargetId;
    private Bundle mBundle;
    private Conversation.ConversationType mConversationType;

    /**
     * 进入页面会初始化加载数据，所以这里默认为true
     */
    private boolean isDataLoading = true;
    private boolean isDataEnd;
    private int currentVisiblePosition = -1;

    /**
     * 所有消息都会在这里回调
     */
    Observer<List<UiMessage>> mListObserver = new Observer<List<UiMessage>>() {
        @Override
        public void onChanged(List<UiMessage> uiMessages) {
            MessageFragment.this.refreshList(uiMessages);
        }
    };

    Observer<Integer> mNewMessageUnreadObserver = count -> {
        if (RongConfigCenter.conversationConfig().isShowNewMessageBar(MessageFragment.this.mMessageViewModel.getCurConversationType())) {
            if (count != null && count > 0) {
                MessageFragment.this.mNewMessageNum.setVisibility(View.VISIBLE);
                MessageFragment.this.mNewMessageNum.setText(count > 99 ? "99+" : String.valueOf(count));
            } else {
                MessageFragment.this.mNewMessageNum.setVisibility(View.INVISIBLE);
            }
        }
    };

    Observer<PageEvent> mPageObserver = new Observer<PageEvent>() {
        @Override
        public void onChanged(PageEvent event) {

            for (IConversationUIRenderer processor : RongConfigCenter.conversationConfig().getViewProcessors()) {
                if (processor.handlePageEvent(event)) {
                    return;
                }
            }

            if (event instanceof Event.RefreshEvent) {
                if (((Event.RefreshEvent) event).state.equals(RefreshState.RefreshFinish)) {
                    MessageFragment.this.mRefreshLayout.finishRefresh();
                } else if (((Event.RefreshEvent) event).state.equals(RefreshState.LoadFinish)) {
                    MessageFragment.this.mRefreshLayout.finishLoadMore();
                }

            } else if (event instanceof ToastEvent) {
                String msg = ((ToastEvent) event).getMessage();
                if (!TextUtils.isEmpty(msg)) {
                    Toast.makeText(MessageFragment.this.getContext(), msg, Toast.LENGTH_SHORT).show();
                }
            } else if (event instanceof ScrollToEndEvent) {
                MessageFragment.this.mList.scrollToPosition(MessageFragment.this.mAdapter.getItemCount() - 1);
            } else if (event instanceof ScrollMentionEvent) {
                MessageFragment.this.mMessageViewModel.onScrolled(MessageFragment.this.mList, 0, 0, MessageFragment.this.mAdapter.getHeadersCount(), MessageFragment.this.mAdapter.getFootersCount());
            } else if (event instanceof ScrollEvent) {
                MessageFragment.this.mList.scrollToPosition(MessageFragment.this.mAdapter.getHeadersCount() + ((ScrollEvent) event).getPosition());
            } else if (event instanceof SmoothScrollEvent) {
                MessageFragment.this.mList.scrollToPosition(MessageFragment.this.mAdapter.getHeadersCount() + ((SmoothScrollEvent) event).getPosition());
            } else if (event instanceof ShowLongClickDialogEvent) {
                final MessageItemLongClickBean bean = ((ShowLongClickDialogEvent) event).getBean();
                final List<MessageItemLongClickAction> messageItemLongClickActions = bean.getMessageItemLongClickActions();
                Collections.sort(messageItemLongClickActions, new Comparator<MessageItemLongClickAction>() {
                    @Override
                    public int compare(MessageItemLongClickAction lhs, MessageItemLongClickAction rhs) {
                        return rhs.priority - lhs.priority;
                    }
                });
                List<String> titles = new ArrayList();

                for (MessageItemLongClickAction action : messageItemLongClickActions) {
                    titles.add(action.getTitle(MessageFragment.this.getContext()));
                }

                if (titles.isEmpty()) {
                    return;
                }

                if (bean.getUiMessage() == null) {
                    return;
                }

                OptionsPopupDialog dialog = OptionsPopupDialog.newInstance(MessageFragment.this.getContext(),
                        titles.toArray(new String[titles.size()])).setOptionsPopupDialogListener(which ->
                        messageItemLongClickActions.get(which).listener.onMessageItemLongClick(MessageFragment.this.getContext(), bean.getUiMessage())
                );
                MessageItemLongClickActionManager.getInstance().setLongClickDialog(dialog);
                MessageItemLongClickActionManager.getInstance().setLongClickMessage(bean.getUiMessage().getMessage());
                dialog.setOnDismissListener(dialog1 -> {
                    MessageItemLongClickActionManager.getInstance().setLongClickDialog(null);
                    MessageItemLongClickActionManager.getInstance().setLongClickMessage(null);
                });
                dialog.show();
            } else if (event instanceof PageDestroyEvent) {
                FragmentManager fm = MessageFragment.this.getChildFragmentManager();
                if (fm.getBackStackEntryCount() > 0) {
                    fm.popBackStack();
                } else if (MessageFragment.this.getActivity() != null) {
                    MessageFragment.this.getActivity().finish();
                }
            } else if (event instanceof ShowWarningDialogEvent) {
                MessageFragment.this.onWarningDialog(((ShowWarningDialogEvent) event).getMessage());
            } else if (event instanceof InputBarEvent && ((InputBarEvent) event).mType == InputBarEvent.Type.ReEdit) {
                if (mInputView != null) {
                    mInputView.setEditText(((InputBarEvent) event).mExtra);
                }
            }
        }
    };

    private final RecyclerView.OnScrollListener mScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            MessageFragment.this.mMessageViewModel.onScrolled(recyclerView, dx, dy, MessageFragment.this.mAdapter.getHeadersCount(), MessageFragment.this.mAdapter.getFootersCount());
            currentVisiblePosition = mLinearLayoutManager.findFirstVisibleItemPosition();
            if (mLinearLayoutManager != null && currentVisiblePosition == 0 && !isDataLoading && !isDataEnd) {
                try {
                    isDataLoading = true;
                    mList.postDelayed(() -> {
                        if (mMessageViewModel != null) {
                            mMessageViewModel.onRefresh();
                        }
                    }, 200);
                } catch (NullPointerException e) {
                    isDataLoading = false;
                }
            }
        }
    };

    public MessageFragment() {

    }

    @Override
    @Nullable
    @SuppressLint({"ClickableViewAccessibility"})
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_message, container, false);
        this.mRefreshLayout = rootView.findViewById(id.rc_refresh);
        this.mList = rootView.findViewById(id.rc_message_list);
        this.mNewMessageNum = rootView.findViewById(id.rc_new_message_number);
        this.mUnreadHistoryMessageNum = rootView.findViewById(id.rc_unread_message_count);
        this.mUnreadMentionMessageNum = rootView.findViewById(id.rc_mention_message_count);
        this.mNewMessageNum.setOnClickListener(this);
        this.mUnreadHistoryMessageNum.setOnClickListener(this);
        this.mUnreadMentionMessageNum.setOnClickListener(this);
        this.mLinearLayoutManager = new LinearLayoutManager(this.getContext());
        this.mLinearLayoutManager.setStackFromEnd(true);
        this.mList.setLayoutManager(this.mLinearLayoutManager);
        this.mList.setOnTouchListener((v, event) -> {
            MessageFragment.this.closeExpand();
            return false;
        });

        this.mRefreshLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            @SuppressLint({"ClickableViewAccessibility"})
            public boolean onTouch(View v, MotionEvent event) {
                MessageFragment.this.closeExpand();
                return false;
            }
        });

        this.mAdapter.setItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, ViewHolder holder, int position) {
                MessageFragment.this.closeExpand();
            }

            @Override
            public boolean onItemLongClick(View view, ViewHolder holder, int position) {
                return false;
            }
        });
        if (this.mList != null) {
            this.mList.setAdapter(this.mAdapter);
            this.mList.addOnScrollListener(this.mScrollListener);
            this.mList.setItemAnimator(null);
            final GestureDetector gd = new GestureDetector(this.getContext(), new GestureDetector.SimpleOnGestureListener() {
                @Override
                public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                    MessageFragment.this.closeExpand();
                    return super.onScroll(e1, e2, distanceX, distanceY);
                }
            });
            this.mList.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
                @Override
                public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
                    return gd.onTouchEvent(e);
                }

                @Override
                public void onTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
                }

                @Override
                public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
                }
            });
        }

        this.mRefreshLayout.setNestedScrollingEnabled(false);
        this.mRefreshLayout.setRefreshHeader(new RongRefreshHeader(this.getContext()));
        this.mRefreshLayout.setRefreshFooter(new RongRefreshHeader(this.getContext()));
        this.mRefreshLayout.setEnableRefresh(true);
        this.mRefreshLayout.setOnRefreshListener(this);
        this.mRefreshLayout.setOnLoadMoreListener(this);
        initViews(rootView); //新代码加入的
        return rootView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        if (this.getActivity() != null && this.getActivity().getIntent() != null) {
            super.onViewCreated(view, savedInstanceState);
            Intent intent = this.getActivity().getIntent();
            if (this.mTargetId == null) {
                this.mTargetId = intent.getStringExtra("targetId");
            }

            if (this.mConversationType == null) {
                String type = intent.getStringExtra("ConversationType");
                if (type != null) {
                    this.mConversationType = Conversation.ConversationType.valueOf(type.toUpperCase(Locale.US));
                }
            }

            if (this.mBundle == null) {
                this.mBundle = intent.getExtras();
            }

            this.mMessageViewModel = (new ViewModelProvider(this)).get(MessageViewModel.class);
            this.bindConversation(this.mTargetId, this.mConversationType, this.mBundle);

            this.onViewCreated = true;
        } else {
            RLog.e(this.TAG, "Must put targetId and conversation type to intent when start conversation.");
        }
    }

    public void initConversation(String targetId, Conversation.ConversationType conversationType, Bundle bundle) {
        if (this.onViewCreated) {
            this.bindConversation(targetId, conversationType, bundle);
        } else {
            this.mTargetId = targetId;
            this.mConversationType = conversationType;
            this.mBundle = bundle;
        }
    }

    private void bindConversation(String targetId, Conversation.ConversationType conversationType, Bundle bundle) {
        if (conversationType != null && !TextUtils.isEmpty(targetId)) {
            this.mMessageViewModel.bindConversation(conversationType, targetId, bundle);
            this.subscribeUi();
        } else {
            RLog.e(this.TAG, "Invalid intent data !!! Must put targetId and conversation type to intent.");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (this.getView() != null) {
            this.mMessageViewModel.onResume();
            this.getView().setOnKeyListener(new View.OnKeyListener() {
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    return (event.getAction() == 1 && keyCode == 4) && MessageFragment.this.onBackPressed();
                }
            });
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        this.mMessageViewModel.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        this.mMessageViewModel.onStop();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

        for (IConversationUIRenderer processor : RongConfigCenter.conversationConfig().getViewProcessors()) {
            processor.onDestroy();
        }

        this.mList.removeOnScrollListener(this.mScrollListener);
        if (this.mMessageViewModel != null) {
            this.mMessageViewModel.getPageEventLiveData().removeObserver(this.mPageObserver);
            this.mMessageViewModel.getUiMessageLiveData().removeObserver(this.mListObserver);
            this.mMessageViewModel.onDestroy();
        }

        destroyExtension();
    }

    private void subscribeUi() {
        this.mMessageViewModel.getPageEventLiveData().observeForever(this.mPageObserver);
        this.mMessageViewModel.getUiMessageLiveData().observeForever(this.mListObserver);
        this.mMessageViewModel.getNewMessageUnreadLiveData().observe(this.getViewLifecycleOwner(), this.mNewMessageUnreadObserver);
    }

    @Override
    public void onViewClick(int clickType, UiMessage data) {
        this.mMessageViewModel.onViewClick(clickType, data);
    }

    @Override
    public boolean onViewLongClick(int clickType, UiMessage data) {
        return this.mMessageViewModel.onViewLongClick(clickType, data);
    }

    private void refreshList(final List<UiMessage> data) {
        if (this.mList.isComputingLayout()) {
            this.mList.postDelayed(() -> MessageFragment.this.refreshList(data), 50);
        } else {
            if (currentVisiblePosition == 0 && mAdapter.getData().size() == data.size()) {
                isDataEnd = true;
            }
            if (mAdapter.getData().size() == 0) {
                mAdapter.setDataCollection(data);
                mList.postDelayed(() -> {
                    mLinearLayoutManager.scrollToPositionWithOffset(mAdapter.getItemCount() - 1, Integer.MIN_VALUE);
                }, 200);
            } else {
                mAdapter.setDataCollection(data);
            }
            isDataLoading = false;
        }
    }

    public boolean onBackPressed() {
        boolean result = false;

        for (IConversationUIRenderer processor : RongConfigCenter.conversationConfig().getViewProcessors()) {
            boolean temp = processor.onBackPressed();
            if (temp) {
                result = true;
            }
        }

        if (this.mMessageViewModel != null) {
            boolean temp = this.mMessageViewModel.onBackPressed();
            if (temp) {
                result = true;
            }
        }

        return result;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1000) {
            if (grantResults.length > 0 && grantResults[0] == 0) {
                HQVoiceMsgDownloadManager.getInstance().resumeDownloadService();
            } else {
                PermissionCheckUtil.showRequestPermissionFailedAlter(this.getContext(), permissions, grantResults);
            }

        } else {
            if (requestCode == 100 && grantResults.length > 0 && grantResults[0] != 0) {
                PermissionCheckUtil.showRequestPermissionFailedAlter(this.getContext(), permissions, grantResults);
            }
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.rc_new_message_number) {
            this.mMessageViewModel.newMessageBarClick();
        } else if (id == R.id.rc_unread_message_count) {
            this.mMessageViewModel.unreadBarClick();
        } else if (id == R.id.rc_mention_message_count) {
            this.mMessageViewModel.newMentionMessageBarClick();
        }
    }

    public void onWarningDialog(String msg) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
        builder.setCancelable(false);
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();
        Window window = alertDialog.getWindow();
        if (window != null) {
            window.setContentView(R.layout.rc_cs_alert_warning);
            TextView tv = window.findViewById(id.rc_cs_msg);
            tv.setText(msg);
            window.findViewById(id.rc_btn_ok).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alertDialog.dismiss();
                    FragmentManager fm = MessageFragment.this.getChildFragmentManager();
                    if (fm.getBackStackEntryCount() > 0) {
                        fm.popBackStack();
                    } else if (MessageFragment.this.getActivity() != null) {
                        MessageFragment.this.getActivity().finish();
                    }
                }
            });
        }
    }

    private void closeExpand() {
        if (null != mInputView) {
            mInputView.dismissMenuLayout();
        }
    }

    protected MessageListAdapter onResolveAdapter() {
        return new MessageListAdapter(this);
    }

    public void addHeaderView(View view) {
        this.mAdapter.addHeaderView(view);
    }

    public void addFooterView(View view) {
        this.mAdapter.addFootView(view);
    }

    public void setEmptyView(View view) {
        this.mAdapter.setEmptyView(view);
    }

    public void setEmptyView(@LayoutRes int emptyId) {
        this.mAdapter.setEmptyView(emptyId);
    }

    //-------------------------------------------------------------

    private final int REQUEST_IMAGE = 0x00000011;

    private static final int REQUEST_CS_LEAVEL_MESSAGE = 102;

    //输入模块
    private ChatInputView mInputView;

    private EmoticonsEditText auroraEtChatInput;

    private InputMethodManager mImm;

    private Window mWindow;

    //草稿内容
    private String mDraft;

    private final List<Subscription> mSubscriptions = new ArrayList<>();

    private void initViews(View view) {
        initCustom(view);
        getTextMessageDraft();
    }

    private void initCustom(View view) {
        mWindow = getActivity().getWindow();
        mWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
                | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        this.mImm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);

        mInputView = view.findViewById(id.chat_input);
        mInputView.setActivity(getActivity());
        ChatInputLoadManager.getInstance().sendInputView(mInputView);
        auroraEtChatInput = mInputView.findViewById(R.id.aurora_et_chat_input_1);

        Subscription s1 = RxBus.getDefault().observerRxBus(ShowSoftKeyboardEvent.class, event -> {
            auroraEtChatInput.postDelayed(new Runnable() {
                @Override
                public void run() {
                    KeyboardUtils.showSoftInput(auroraEtChatInput, InputMethodManager.RESULT_UNCHANGED_SHOWN);
                }
            }, 300);
        });
        mSubscriptions.add(s1);

        // 处理键盘逻辑
        mInputView.setGroupChat(getTargetId());
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        if (this.mMessageViewModel != null) {
            this.mMessageViewModel.onLoadMore();
        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        try {
            if (this.mMessageViewModel != null) {
                this.mMessageViewModel.onRefresh();
            }
        } catch (NullPointerException ignored) {

        }
    }

    public interface OnSendTextSuccessListener {
        void onSuccess();
    }

    public void onSendToggleClick(View v, String text, String isServer, OnSendTextSuccessListener listener) {
        if (TextUtils.isEmpty(text) || TextUtils.isEmpty(text.trim())) {
            RLog.e(TAG, "text content must not be null");
            return;
        }
        TextMessage textMessage = TextMessage.obtain(text);
        io.rong.imlib.model.Message message = io.rong.imlib.model.Message.obtain(mTargetId, mConversationType, textMessage);

        RongIM.getInstance().sendMessage(message, null, null, new IRongCallback.ISendMessageCallback() {
            @Override
            public void onAttached(io.rong.imlib.model.Message message) {
                LogDataUtils.d("sendMessage", "onAttached\t\t" + message.getSentStatus().getValue() + "\t\t" + message.getReceivedStatus().getFlag());
            }

            @Override
            public void onSuccess(io.rong.imlib.model.Message message) {
                LogDataUtils.d("sendMessage", "onSuccess\t\t" + message.getSentStatus().getValue() + "\t\t" + message.getReceivedStatus().getFlag());
                if (listener != null) {
                    listener.onSuccess();
                }
            }

            @Override
            public void onError(io.rong.imlib.model.Message message, RongIMClient.ErrorCode errorCode) {
                LogDataUtils.d("sendMessage", "onError\t\t" + errorCode.getValue());
            }
        });
    }

    public String getTargetId() {
        return mTargetId;
    }

    public void selectPhoto() {
        PictureSelector.create(this)
                .openGallery(RongConfigCenter.conversationConfig().rc_media_selector_contain_video ? PictureMimeType.ofAll()
                        : PictureMimeType.ofImage()).loadImageEngine(RongConfigCenter.featureConfig().getKitImageEngine()).setRequestedOrientation(1)
                .videoDurationLimit(RongIMClient.getInstance().getVideoLimitTime()).maxSelectNum(9).imageSpanCount(3).isGif(true).forResult(REQUEST_IMAGE);
    }

    /**
     * 发送骰子
     */
    public void sendChatRoomEmoijShaiZiMessage(String content, int result) {
        RXDiceMessageContent messageContent = new RXDiceMessageContent();
        messageContent.setContent(String.valueOf(result));
        Conversation.ConversationType conversationType = Conversation.ConversationType.PRIVATE;
        io.rong.imlib.model.Message message = io.rong.imlib.model.Message.obtain(mTargetId, conversationType, messageContent);
        RongIM.getInstance().sendMessage(message, null, null, null);
    }

    public void notifyDataSetChanged() {
        if (this.mAdapter != null) {
            this.mAdapter.notifyDataSetChanged();
        }
    }

    public void onImageResult(Intent data) {

        List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
        if (selectList != null && selectList.size() > 0) {
            boolean sendOrigin = selectList.get(0).isOriginal();
            for (LocalMedia item : selectList) {
                String mimeType = item.getMimeType();
                if (mimeType.startsWith("image")) {
                    SendImageManager.getInstance().sendImage(this.mConversationType, mTargetId, item, sendOrigin);
                    if (this.mConversationType.equals(Conversation.ConversationType.PRIVATE)) {
                        RongIMClient.getInstance().sendTypingStatus(this.mConversationType, mTargetId, "RC:ImgMsg");
                    }
                } else if (mimeType.startsWith("video")) {
                    Uri path = Uri.parse(item.getPath());
                    if (TextUtils.isEmpty(path.getScheme())) {
                        path = Uri.parse("file://" + item.getPath());
                    }

                    SendMediaManager.getInstance().sendMedia(IMCenter.getInstance().getContext(), this.mConversationType, mTargetId, path, item.getDuration());
                    if (this.mConversationType.equals(Conversation.ConversationType.PRIVATE)) {
                        RongIMClient.getInstance().sendTypingStatus(this.mConversationType, mTargetId, "RC:SightMsg");
                    }
                }
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if (requestCode == REQUEST_CODE_FORWARD) {
                this.mMessageViewModel.forwardMessage(data);
            } else if (requestCode == REQUEST_CS_LEAVEL_MESSAGE) {
                getActivity().finish();
            } else if (requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK) {
                onImageResult(data);
            }
        } catch (Exception ignored) {

        }
    }

    private void scrollToBottom() {
        this.mList.smoothScrollToPosition(0);
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                ChatInputView chatInputView = mInputView;
                if (view.getId() == chatInputView.getInputView().getId()) {
                    scrollToBottom();
                    if (chatInputView.getMenuState() == View.VISIBLE
                            && !chatInputView.getSoftInputState()) {
                        chatInputView.dismissMenuAndResetSoftMode();
                    }
                    return false;
                }
                if (chatInputView.getMenuState() == View.VISIBLE) {
                    chatInputView.dismissMenuLayout();
                }
                if (chatInputView.getMoreState() == View.VISIBLE) {
                    chatInputView.dismissMenuLayout();
                }
                try {
                    View v = getActivity().getCurrentFocus();
                    if (mImm != null && v != null) {
                        mImm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                        mWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
                                | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                        view.clearFocus();
                        chatInputView.setSoftInputState(false);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case MotionEvent.ACTION_UP:
                view.performClick();
                break;
        }
        return false;
    }

    /**
     * 移除扩展项
     */
    private void destroyExtension() {
        String text = mInputView.getInputEditText().getText().toString();
        String mentionInfo = RongMentionManager.getInstance().getMentionBlockInfo();
        String saveDraft = DraftHelper.encode(text, mentionInfo);

        if ((TextUtils.isEmpty(text) && !TextUtils.isEmpty(mDraft))
                || (!TextUtils.isEmpty(text) && TextUtils.isEmpty(mDraft))
                || (!TextUtils.isEmpty(text) && !TextUtils.isEmpty(mDraft) && !text.equals(mDraft))) {
            if (TextUtils.isEmpty(saveDraft)) {
                IMCenter.getInstance().clearTextMessageDraft(mConversationType, mTargetId, null);
            } else {
                IMCenter.getInstance().saveTextMessageDraft(mConversationType, mTargetId, saveDraft, null);
            }
        }
    }

    /**
     * 获取草稿
     */
    private void getTextMessageDraft() {
        try {
            RongIMClient.getInstance().getTextMessageDraft(mConversationType, mTargetId, new RongIMClient.ResultCallback<String>() {
                @Override
                public void onSuccess(String s) {
                    DraftHelper draftHelper = new DraftHelper(s);
                    mDraft = draftHelper.decode();
                    if (!TextUtils.isEmpty(mDraft)) {
                        EmoticonsEditText editText = mInputView.getInputEditText();
                        editText.setText(mDraft);
                        draftHelper.restoreMentionInfo();
                        editText.setSelection(editText.length());
                        editText.requestFocus();
                    }
                }

                @Override
                public void onError(RongIMClient.ErrorCode e) {

                }
            });
        } catch (Exception ignored) {

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        for (Subscription subscription : mSubscriptions) {
            if (subscription == null) {
                continue;
            }
            if (subscription.isUnsubscribed()) {
                continue;
            }
            subscription.unsubscribe();
        }
        mSubscriptions.clear();
    }
}
